/**
 * 
 */
 
jQuery(function(){
	//generatePoster();
});

var geneFlag=0;
var image,ratio;
var c;
function generatePoster(){
	
	c=document.getElementById("poster");
	c.width=templateImgWidth;
	c.height=templateImgHeight;
	var ctx=c.getContext("2d");
	//ctx.fillStyle = "#FFFFFF";
	 //调用 调节清晰度方法
	ratio = getPixelRatio(ctx);
	//ctx.fillRect(0,0,templateImgWidth*ratio,templateImgHeight*ratio);
	//generateElem(ctx,0)
	//创建image对象
	image= new Image();
	image.src=templateImgPath;
	//图片加载完成，将其显示在canvas上
	image.onload=function(){
		ctx.drawImage(this,0,0,templateImgWidth,templateImgHeight);
		if(elements.length>0){
			generateElem(ctx,0)
		}
	}
}

function generateElem(ctx,i){
	if(i==elements.length){
		$("#poster2").attr("src",c.toDataURL());
		return ;
	}
	var elem=elements[i];
	i++;
	//判断元素类型
	if(elem.elementType=="text"||elem.elementType=="slogan"){
		//文本
		//ctx.fillStyle = "#333";
		ctx.font=elem.elementStyle;
		var elems=elem.elementContent.split("-");
		ctx.fillText("   "+elems[0],elem.positionX,elem.positionY);
		if(elems[1].length<6){
			ctx.fillText("   "+elems[1],elem.positionX,elem.positionY+30);
		}else{
			var j=elems[1].length/5;
			for (var k = 0; k < j; k++) {
				if(k==0){
					ctx.fillText("   "+elems[1].substring(k*5,(k+1)*5),elem.positionX,elem.positionY+((k+1)*30));
				}else{
					if(k==1){
						ctx.fillText(elems[1].substring(k*5,(k+1)*6),elem.positionX,elem.positionY+((k+1)*30));
					}else if(k==2){
						ctx.fillText(elems[1].substring(k*6,(k+1)*6)+"...",elem.positionX,elem.positionY+((k+1)*30));
					}
				}
			}
		}
		generateElem(ctx,i);
	}else{
		//image= new Image();
		image.src=elem.elementContent;
		image.onload=function(){
			ctx.drawImage(this,elem.positionX,elem.positionY,elem.width,elem.height);
			generateElem(ctx,i)
		}
	}
}

/**
 * 调节清晰度
 * @param {} context
 * @return {}
 */
var getPixelRatio = function(context) {
  var backingStore = context.backingStorePixelRatio ||
    context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1;
   return (window.devicePixelRatio || 1) / backingStore;
};